package com.netty.esc.config.websocket;


//import com.netty.esc.netty.server.ServerIdleStateTrigger;

import com.netty.esc.service.action.ApplicationEventCenter;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: zhaoyang
 * @Data: 2022/5/1 11:29
 * @Description
 * 启动类
 */
@Component
@ChannelHandler.Sharable
@PropertySource("classpath:application.properties")
@Slf4j
public class WebSocketServer {
    @Resource
    WebServerChannelInitializer webServerChannelInitializer;
//    @Autowired
//    ServerIdleStateTrigger serverIdleStateTrigger;
//    @Resource
//    PushProductTimer pushProductTimer;

    public static  EventLoopGroup bossGroup = new NioEventLoopGroup();
    public static  EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Value("${websocket}")
    public Integer port;


    @Async
    public void start() throws InterruptedException {
        log.info("启动websocket，监听端口：" + port);
        WebSocketServerHandler.PORT = port;
        try {
            //socket启动后，初始化函数存储器。
             ApplicationEventCenter.getInstance().init();
            //如果项目启动时在推送时间段，主动调用一次。
//            if (TimeUtil.isPushPeriod()){
//                pushProductTimer.startTask();
//            }
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(webServerChannelInitializer);
            Channel ch = b.bind(port).sync().channel();
            System.out.println("Web socket server started at port " + port
                    + '.');
            System.out
                    .println("Open your browser and navigate to http://localhost:"
                            + port + '/');

            ChannelFuture sync = ch.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
